<template>
  <div class="flex h-full">
    <a-card
      class="pt-2 mr-2 min-w-fit h-full w-[320px]"
      size="small"
      :body-style="{ height: '100%', padding: '0 8px', display: 'flex', flexDirection: 'column' }"
    >
      <SearchComb placeholder="姓名/助记码/卡号/手机号/身份证号" @search="queryList" />
      <BaseList :data-source="listDataSource" :loading="loading" class="flex-1 overflow-auto w-full">
        <template #renderItem="{ item }">
          <div class="py-2 px-3" :class="patientInfo.lsh === item.lsh ? 'active' : ''" @click="onSelectPatient(item)">
            <div class="flex justify-between mb-2">
              <div class="flex">
                <LabelValue class="text-primary text-base font-bold" :width="80" :value="item.brName" />
                <!-- <div class="w-[90px]">{{ item.brName }}</div> -->
                <span>{{ item.brXb }}</span>
                <span class="ml-2">{{ item.brAge }}</span>
              </div>
              <div>{{ item.sfsc }}</div>
            </div>
            <div class="flex justify-between">
              <LabelValue :width="32" :value="item.oprEyeType" />
              <div>{{ item.ssys }}</div>
              <div>{{ item.oprDate }} {{ item.oprTime }}</div>
            </div>
          </div>
        </template>
      </BaseList>
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <PatientInfoHeader :patient-info="patientInfo" @change="queryList">
        <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
        <div>
          <div class="flex items-center">
            <LabelValue class="ml-4" :label="isBJMSG ? '病历号' : '手术病案号'" :width="200" :value="patientInfo?.sfsc" />
            <LabelValue class="ml-4" label="手术医生" :width="210" :value="patientInfo?.ssys" tooltip />
            <LabelValue class="ml-4" label="手术时间" :width="210" :value="patientInfo?.oprDate && patientInfo?.oprDate + ' ' + patientInfo?.oprTime" tooltip />
            <LabelValue class="ml-4" label="麻醉方式" :width="140" :value="patientInfo?.anesthesiaMethodName" tooltip />
          </div>
          <div class="flex items-center">
            <LabelValue class="ml-4" label="眼别" :width="200" :value="patientInfo?.oprEyeType" tooltip />
            <LabelValue class="ml-4" label="右眼手术" :width="210" :value="patientInfo?.odmc" tooltip />
            <LabelValue class="ml-4" label="左眼手术" :width="210" :value="patientInfo?.osmc" tooltip />
            <LabelValue class="ml-4" label="咨询师" :width="140" :value="patientInfo?.zxysName" tooltip />
          </div>
        </div>
      </PatientInfoHeader>
      <div class="flex flex-1 mt-2 overflow-hidden">
        <a-card class="flex-1 overflow-auto" :body-style="{ padding: '0 8px', height: '100%', overflow: 'hidden' }">
          <a-tabs
            v-model:activeKey="activeKey"
            destroy-inactive-tab-pane
            :class="store.currentPatient?.jzbh ? 'h-full' : 'tabs-disabled h-full'"
            @change="onChangeTabs"
          >
            <a-tab-pane key="1" tab="病历">
              <TabCase :case-data="patientData" :active-key="activeKey" @success="onCaseSuccess" />
            </a-tab-pane>
            <a-tab-pane v-if="!systemConfig.isMedicine" key="3" tab="处置">
              <TabDispose />
            </a-tab-pane>
            <a-tab-pane v-if="!systemConfig.isMedicine" key="4" tab="西成药" :disabled="!isHasDiagnosis && systemConfig.isWestMedicine">
              <TabWesternMedicine />
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import SearchComb from '@/components/SearchComb'
import PatientInfoHeader from '@/components/business/PatientInfoHeader'
import { post } from '@/utils/request'
import BaseList from '@/components/BaseList'
import { getSystemConfig } from '@/utils/systemConfig'
import useStore from '@/views/out-doctor/store'

import TabCase from '@/views/out-doctor/workstation/TabCase'
import TabDispose from '@/views/out-doctor/workstation/TabDispose'
import TabWesternMedicine from '@/views/out-doctor/workstation/TabWesternMedicine'

const router = useRouter()
const store = useStore()
const loading = ref(false)
const isAutoCode = ref(false)
const listDataSource = ref([])
const patientInfo = ref({})
const params = ref({})
const activeKey = ref(router.currentRoute.value.query.tab || '1')

const systemConfig = {
  isMedicine: getSystemConfig('ENABLE_OUTP__SINGLE_ADVICEORDER_MODE') === '1', //0处置、西成药1医嘱
  isWestMedicine: getSystemConfig('ISSUE_DRUG_ORDER_WITHOUT_ICD10') === '0' // 西成药
}
const patientData = ref({})
const isHasDiagnosis = ref(false)
const patientListRef = ref()

//左侧数据
const queryList = async (param = {}) => {
  if (param?.endDate) params.value = param
  loading.value = true
  const { code, data, msg } = await post('/operation/opex/getDuringSurgeryPatientList', {
    zjm: params.value?.searchKey,
    eddate: params.value?.endDate,
    stdate: params.value?.startDate
  })
  loading.value = false
  if (code !== 0) return message.error(msg)
  listDataSource.value = data
  if (data && data.length) {
    patientInfo.value = data[0]
    store.currentPatient = data[0]
    onSelectPatient(patientInfo.value)
    getData(patientInfo.value.jzbh)
  }
}
const getData = async (jzbh) => {
  const { code, msg, data } = await post('/outp/mzys/getOutpRecordInfo', {
    mzjlbh: jzbh
  })
  if (code !== 0) return message.error(msg || '获取病历信息失败')
  patientData.value =
    {
      ...data,
      assistant1EmpId: data.assistant1EmpId ?? patientData.value?.assistant1EmpId,
      assistant1EmpName: data.assistant1EmpName ?? patientData.value?.assistant1EmpName
    } || {}
  if (!data?.assistant1EmpId && patientData.value?.assistant1EmpId && getSystemConfig('IS_DOCTOR_ASSISTANT') === '1') {
    onSelectAssistant1({ empId: patientData.value?.assistant1EmpId, empName: patientData.value?.assistant1EmpName }, true)
  }
  if (patientData.value?.bcLczdZdmc) {
    isHasDiagnosis.value = true
  } else {
    isHasDiagnosis.value = false
  }
}
const onSelectAssistant1 = async (select, type) => {
  patientData.value.assistant1EmpId = select.empId
  patientData.value.assistant1EmpName = select.empName
  if (!patientData.value.jzbh) return
  const { code, msg } = await post(`outp/mzys/upAssistant`, { assistant1EmpId: select.empId, jzbh: patientData.value.jzbh })
  if (code !== 0) return message.error(msg || '失败')
  if (!type) {
    message.success('操作成功')
  }
}

const isDev = import.meta.env.DEV
//切换Tab标签
const onChangeTabs = () => {
  if (isDev) {
    router.push({
      path: router.currentRoute.value.path,
      query: {
        tab: activeKey.value
      }
    })
  }
}
const onCaseSuccess = () => {
  getData(store.currentPatient.jzbh)
  isHasDiagnosis.value = true
  patientListRef.value?.queryList(false)
}
const onSelectPatient = (row) => {
  patientInfo.value = { ...row }
  store.currentPatient = { ...row }
}
watch(
  () => store.currentPatient.jzbh,
  (val) => {
    if (val) {
      getData(val)
    } else {
      patientData.value = {}
    }
    activeKey.value = '1'
    if (isDev && val) {
      nextTick(() => {
        activeKey.value = router.currentRoute.value.query.tab || '1'
      })
    }
  },
  { immediate: true }
)
const isBJMSG = getSystemConfig('GHDJYS') === '4' //是否北京茗视光
onMounted(() => {
  isAutoCode.value = getSystemConfig('OPERATION_NO_AUTO_GENERATE') === '1' // 病案号自动生成，0：手动，1：自动
})
</script>

<style lang="less" scoped></style>
